<template>
  <div class="city-list">
    <van-index-bar :index-list="getCitiesLetter" @select="handleSelect">
      <div v-for="item in cityList" :key="item.type">
        <van-index-anchor :index="item.type"/>
        <van-cell v-for="city in item.cities" :key="city.cityId" :title="city.name"
                  @click="handleChangePage(city.name, city.cityId)"/>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import Vue from 'vue'
import {Cell, IndexAnchor, IndexBar, Toast} from 'vant'
import http from '@/util/http'

Vue.use(IndexBar).use(Cell)
Vue.use(IndexAnchor)
export default {
  name: 'City',
  data() {
    return {
      cityList: []
    }
  },
  computed: {
    getCitiesLetter() {
      return this.cityList.map(item => item.type)
    }
  },
  methods: {
    handleChangePage(name, cityId) {
      this.$store.commit('changeCityName', name)
      this.$store.commit('changeCityId', cityId)
      this.$router.back()
    },
    handleSelect(index) {
      console.log(index)
      Toast(index)
    },
    // TODO: 处理307条数据，将其变成按城市首字母归类。最难的部分
    processData(cities) {
      const letterArray = []
      const result = []
      // 1. 生成26个字母
      for (let code = 65; code < 91; code++) {
        letterArray.push(String.fromCharCode(code))
      }
      letterArray.forEach((letter) => {
        const temp = cities.filter(item => item.pinyin.substring(0, 1).toUpperCase() === letter)
        if (temp.length > 0) {
          result.push({
            type: letter,
            cities: temp
          })
        }
      })
      console.log(result)
      return result
    }
  },
  mounted() {
    http({
      url: 'gateway?k=3331919',
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then(res => {
      this.cityList = this.processData(res.data.data.cities)
    })
  },
}
</script>

<style scoped>

</style>
